<template>
  <div>
    <div ref="letters" class="letters">
      <div
        @touchstart="touchStart"
        @touchmove="touchMove"
        @touchend="flag = false"
        v-for="item in letters"
        :key="item"
      >
        {{ item }}
      </div>
    </div>
    <span v-show="flag" class="dialog">
      {{ letters[index] }}
    </span>
  </div>
</template>

<script>
export default {
  props: ["letters"],
  data() {
    return {
      index: -1,
      flag:false
    };
  },
  methods: {
    getAbsIndex(pageY) {
      let lettersOffsetHeight = this.$refs.letters.offsetHeight; //元素的像素高度404
      // 后面是元素距离顶部的高度，被减之后得到点击位置距离元素顶部距离
      let currentY = pageY - (window.innerHeight - lettersOffsetHeight) / 2; //131.5
      let itemHeight = lettersOffsetHeight / this.letters.length; //A-Z每个元素的高度
      let index = Math.floor(currentY / itemHeight); //所点击元素的索引下标
      if (index < 0) {
        index = 0;
      }
      if (index > this.letters.length - 1) {
        index = this.letters.length - 1;
      }
      this.flag=true;
      this.index = index;
      this.$emit("setIndex", index); //把index抛出给父级，父级监听并作出操作
    },
    touchStart({ touches }) {
      let pageY = touches[0].pageY; //点击位置距离视口顶部高度
      this.getAbsIndex(pageY);
    },
    touchMove({ touches }) {
      let pageY = touches[0].pageY;
      this.getAbsIndex(pageY);
    },
  },
};
</script>

<style lang="scss" scoped>
.letters {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  padding: 4px 6px;
  color: #666;
  line-height: 18px;
}
.dialog {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  background: rgba(0, 0, 0, 0.6);
  position: fixed;
  top: 50%;
  left: 50%;
  text-align: center;
  line-height: 40px;
  color: #fff;
  font-size: 18px;
  transform: translate(-50%, -50%);
}
</style>
